Home |
| Latest | About | Random
# Week 3 Wednesday Dear Class, Today we discuss the idea of **scope** (**section 8.2**), things that are created in the scope are destroyed at the end of the scope. We create a block scope by curly brace `{`, and the scope ends with the matching curly brace `}`. Then we will discuss **while** loops (**section 8.3**), this gives a way to repeat instructions so long as the given condition remain true. Reminders - HW2 due Thursday 10pm. - **Exam 1 Week 5 Monday in-class, will cover up to and including section 8**. -- B. . . . . . . . ## Are you an evil genius? You wrote a program to secretly change one's low score! Where if the score is less than `60`, you make it `100`! Wa-ha-ha! But...were you the evil genius that you thought you were? ```cpp #include using namespace std; int main() { int score; cout << "What is your score? "; cin >> score; if (score < 60) { int score = 100; } cout << "Your score is " << score; return 0; } ``` How would you "fix" it, so it does what you want? . . . . . . . ## Block scope with curly braces `{` and `}`. Whenever you write `{ ... }` (†), things enclosed in a set of matching curly braces `{` and `}`, then you have created a **block scope**. In summary: - An inner scope can access names from the outer scope containing it, as long as the name is declared before the point of use. - An outer scope cannot access names from the inner scope. - The variables declared in the inner scope are **destroyed** when the block ends with `}`. - Non-intersecting scopes do not have access to each other. - If an inner scope declares an identifier (variable name) with the same name as one in an outer scope, the inner one shadows the outer one from its point of declaration to the end of the inner block, including any nested blocks. - Before the inner declaration, the name still refers to the outer identifier. - Generally it is a bad practice to repeat identifier names. It makes code hard to read. († Ok, there are times where `{}` is used differently: Brace initialization (`int x{5};`), initializer lists, and class, namespace, and `enum` bodies are not block scopes.) This applies to scopes created by `if`, `while`, `for`, and `functions` as we shall see. **Illustration 1.** How scopes are created and destroyed, and which has access to what variable. ![[1-teaching/ucla-2026-fall-pic-10a/---files/scope.svg]] . . . . . . . . **Illustration 2.** What happens if we have repeated identifiers. ![[1-teaching/ucla-2026-fall-pic-10a/---files/repeat-identifier.svg]] . . . . . . . . **Practice. Try it!** Let us check this piece of code out. - Can you predict what will happen? - Determine all the lines that will give an error. What kinds of error are they? - After removing all the lines that give error, what is the final output of the program? ```cpp #include using namespace std; int main() { int a = 1; cout << a << endl; int a = 100; { int b = 2; a = a + b; cout << a << endl; int a = 100; cout << a << endl; a = a + b; cout << a << endl; { int c = 3; cout << a << endl; cout << b << endl; cout << c << endl; } cout << a << endl; cout << b << endl; cout << c << endl; { cout << c << endl; int c = 300; cout << c << endl; } } cout << a << endl; cout << b << endl; cout << c << endl; } ``` [[1-teaching/ucla-2026-fall-pic-10a/SCOPE-answers|SCOPE-answers]] . . . . . . . ## `while` loop. A classic classroom punishment is to have the offending student repent their sins by writing on the blackboard repeatedly... ![[1-teaching/ucla-2026-fall-pic-10a/---files/Pasted image 20261013204441.png|The Simpsons. Episode 312 opening sequence chalkboard gag.]] Imagine Bart Simpson here has the power of a `while` loop, which can repeat a task so long as a condition (that evaluates to a `bool`) is `true`. ```cpp #include using namespace std; int main() { while(true){ cout << "SANDWICHES SHOULD NOT CONTAIN SAND" << endl; } return 0; } ``` (**Press `ctrl + c` to send a system interrupt signal to stop this infinite loop!**) . . . . . . . ### How `while` works. In general a `while` loop looks like this: ```cpp while (condition) { statement } ``` Whenever the `condition` evaluates to the `bool` `true`, then the following block scope will be created and the `statement` in it will be executed, then the scope is destroyed. This whole process repeats itself until `condition` evaluates to the `bool` `false`. ![[1-teaching/ucla-2026-fall-pic-10a/---files/while.svg]] . . . . . . . ### Using `break` to break out of the inner most loop If the condition is always `true` like in `while(true){ ... }`, then we get an **infinite loop**. This isn't an undefined behavior per se, and sometimes it is desirable (for example keeping certain process running indefinitely). We have a keyword call `break` to break out of a loop (**and loops only)**. ```cpp #include using namespace std; int main() { const int password = 1234; int input; while(true){ cout << "What is the password? "; cin >> input; if (input == password){ break; } } cout << "You entered the right password!" << endl; return 0; } ``` - `break` breaks out **which ever inner most loop** that contains it, and that one alone. Note, `break` would not break out other scopes (like `if`). It only breaks out of loops, which for us are `while` and `for`. - By the way above is just for illustration and is **not a robust password checker**, since it relied on `cin` and we just trust the user to enter an `int`. What would happen if the user entered `a` instead? Think about how `cin` behaves!! - Also, as it breaks out of the loop, the scope created by this `while` loop is also destroyed. . . . . . . . ### Modify the condition to control the `while` loop. We can control the `while` loop if we can **modify the condition** somehow. Say we want to perform an action exactly 10 times: ```cpp #include using namespace std; int main() { int i = 0; const int N = 10; while (i < N){ cout << "Right now i = " << i << endl; ++i; } cout << "Finally, we end with i = " << i; return 0; } ``` (Later we will see that **using an index to keep track of whether a condition runs for a certain number of times** is sometimes better suited with a `for` loop instead.) . . . . . . . ### Using `while` with unknown number of loops. There is another situation to use a `while` loop, is when we do not know exactly how many times the loop should repeat until it ends, like the "password" example above. But here we can also modify the condition of the while loop, without knowing exactly how many times the loop will be performed. **To give an example, here is a real mathematical mystery....** **Example.** The [Collatz conjecture](https://en.wikipedia.org/wiki/Collatz_conjecture) / the HOTPO conjecture. This is a math conjecture (unsolved problem in 2026) called the **Collatz conjecture** (or **Half Or Triple Plus One** conjecture), which says the following: - Start with any positive integer `N > 1`. We get a **new number** by... - If `N` is even, divide it by `2`. That is, do `N = N / 2` - If `N` is odd, make it bigger by multiplying it by `3` and add `1`. That is, do `N = 3 * N + 1` - Repeat this procedure on this new number. - Then, the conjecture states: **No matter which starting N > 1, this sequence of numbers will always reach 1**. (But we don't know after how many times exactly). ![[1-teaching/ucla-2026-fall-pic-10a/---files/collatz.svg]] **For example.** If we start with `N = 3` then we get `3 10 5 16 8 4 2 1` If we start with `N = 7` then we get `7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1` If we start with `N = 12` then we get `12 6 3 10 5 16 8 4 2 1` Let us write a piece of code to illustrate this, by taking a user input, and use a while loop to print out all the values it goes through with some start `N` value. ```cpp #include using namespace std; int main() { int N; cout << "Please enter an integer > 1: "; cin >> N; // WRITE A while LOOP WITH while (N != 1) { ... } // INSIDE YOU SHOULD PRINT OUT WHAT N IS CURRENTLY // AND USE if-else TO CHECK WHAT TO DO DEPENDING ON EVEN OR ODD. cout << endl << "And we have finally reached " << N; return 0; } ``` [[1-teaching/ucla-2026-fall-pic-10a/collatz|suggested answer to Collatz code]] Remark. Since we don't know whether Collatz conjecture is true or not, this loop might run forever! Also a priori we do not know how long the loop will take with a starting `N`. **BONUS HOMEWORK.** If you manage to prove Collatz conjecture, you will automatically get an A+ in this class and all classes from now on.